#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<unordered_map>
#include<unordered_set>
#include<climits>
#define int long long 
#define x first 
#define y second 
using namespace std;
const int N = 1e5 + 10;
const int INF = INT_MAX;
vector<vector<vector<int>>>  g(110,vector<vector<int>>(110,vector<int>()));//三维数组
void solve()
{
     int n,m,k,t;
     cin >> n >> m >> k >> t;
     while(t -- )
     {
        int a,x1,y1;
        cin >> a >> x1 >> y1;
        if(g[x1][y1].empty()||g[x1][y1].size() < k)
        {
            g[x1][y1].push_back(a);
            cout << "-1" << endl;
        }
        else   
        {
            int c = INF;
            for(int i = k - 1; i >= 0; i--)
            {
                if(c > g[x1][y1][i]) c = g[x1][y1][i];
            }
            for(int i = k - 1; i >= 0; i--)//越往上的日记本越在数组里面，所以倒着遍历找最小值
            {
                if(c == g[x1][y1][i]) 
                {
                    cout << c << " " << k - i - 1 <<  endl;//输出编号以及移动日记本数目
                    g[x1][y1].erase(g[x1][y1].begin() + i);
                    break;//防止编号相同的继续被销毁
                }
            }
            g[x1][y1].push_back(a);
        }
     }     
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t = 1;
    while(t--) solve();
    return 0;
}